#! /usr/bin/env python

from __future__ import unicode_literals
from __future__ import print_function

import os
import tornado
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.autoreload

import controller

try:
    FileNotFoundError
except NameError:
    FileNotFoundError = IOError

class UpdaterApp(tornado.web.Application):
    def __init__(self):
        settings = dict(
            xsrf_cookies = False,
            debug=True,
            autoreload=True,
        )

        handlers = [
            (r'/latest/([a-zA-Z0-9.-_]+)', controller.LatestVersion),     # get/post
            (r'/version/([a-zA-Z0-9.-_]+)', controller.Version),          # get/post
            (r'/cached/([0-9a-f]{40})', controller.Cached),               # get/post/head
            (r'/required/([a-zA-Z0-9.-_]+)', controller.MinimumRequired), # get/post
            (r'/alias/([a-zA-Z0-9.-_]+)', controller.Alias),              # post
            (r'/merge/([a-zA-Z0-9.-_]+)', controller.Merge),              # post
        ]
        tornado.web.Application.__init__(self, handlers, **settings)
        self.store = os.getcwd() + '/store'
        self.cached = self.store + '/cached'
        try:
            os.stat(self.store)
        except (OSError, FileNotFoundError):
            os.mkdir(self.store)
        try:
            os.stat(self.cached)
        except (OSError, FileNotFoundError):
            os.mkdir(self.cached)

def main():
    http_server = tornado.httpserver.HTTPServer(UpdaterApp())
    http_server.listen(9898)
    io_loop = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.start(io_loop=io_loop, check_time=3000)
    io_loop.start()

if __name__ == "__main__":
    main()
